package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.UserRegisterBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_5_user_user_register_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_5_user_user_register_window().init(
                5005,
                3,
                "DwsApp_5_user_user_register_window",
                Constant.TOPIC_DWD_USER_REGISTER
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 过滤数据，封装为pojo
        SingleOutputStreamOperator<UserRegisterBean> beanDs = toUserRegisterBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<UserRegisterBean> resultDs = windowAndAgg(beanDs);
        // 3 将数据写入Clickhouse
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_USER_USER_REGISTER_WINDOW,UserRegisterBean.class));
    }

    private SingleOutputStreamOperator<UserRegisterBean> windowAndAgg(SingleOutputStreamOperator<UserRegisterBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<UserRegisterBean> strategy = WatermarkStrategy.<UserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<UserRegisterBean>() {
                    @Override
                    public UserRegisterBean reduce(UserRegisterBean t1, UserRegisterBean t2) throws Exception {
                        t2.setRegisterCt(t2.getRegisterCt() + t1.getRegisterCt());
                        return t2;
                    }
                }, new AllWindowFunction<UserRegisterBean, UserRegisterBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserRegisterBean> values, Collector<UserRegisterBean> out) throws Exception {
                        UserRegisterBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }


    private SingleOutputStreamOperator<UserRegisterBean> toUserRegisterBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
                .map(j -> UserRegisterBean.builder().registerCt(1L).ts(j.getLong("create_time")).build());
    }
}
